package com.ar.mylibrary;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.widget.Toast;

public class WifiUtil {

    private static final String TAG = "Main";

    private WifiManager _WifiManager;
    private Context _Context;
    private WifiStateBroadcastReceive mReceive;
    public WifiUtil(Context context) {

        _Context = context;
        _WifiManager = (WifiManager)_Context.getSystemService(Context.WIFI_SERVICE);
    }
    public boolean getWifiState() {
        // 获取蓝牙状态
        return _WifiManager.isWifiEnabled();
    }

    public boolean openWifi() {
        if (getWifiState()) return true;
        // 打开蓝牙
        return _WifiManager.setWifiEnabled(true);
    }

    public boolean cloaseWifi() {
        if (!getWifiState()) return true;
        // 关闭蓝牙
        return _WifiManager.setWifiEnabled(false);
    }

    public void registerWifiReceiver(){
        if(mReceive == null){
            mReceive = new WifiStateBroadcastReceive();
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        _Context.registerReceiver(mReceive, intentFilter);
    }
    public void unregisterWifiReceiver(){
        if(mReceive != null){
            _Context.unregisterReceiver(mReceive);
            mReceive = null;
        }
    }

    class WifiStateBroadcastReceive extends BroadcastReceiver {



        @Override
        public void onReceive(Context context, Intent intent) {

            int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
//            switch (wifiState) {
//                case WifiManager.WIFI_STATE_DISABLED:
//                    Toast.makeText(context , "Wifi已关闭", Toast.LENGTH_SHORT).show();
//                    Log.i(TAG, "onReceive: "+"Wifi已关闭");
//                    break;
//                case WifiManager.WIFI_STATE_DISABLING:
//                    Toast.makeText(context , "Wifi正在关闭", Toast.LENGTH_SHORT).show();
//                    Log.i(TAG, "onReceive: "+"Wifi正在关闭...");
//                    break;
//                case WifiManager.WIFI_STATE_ENABLED:
//                    Toast.makeText(context , "Wifi已打开", Toast.LENGTH_SHORT).show();
//                    Log.i(TAG, "onReceive: "+"Wifi已打开");
//                    break;
//                case WifiManager.WIFI_STATE_ENABLING:
//                    Toast.makeText(context , "Wifi正在打开", Toast.LENGTH_SHORT).show();
//                    Log.i(TAG, "onReceive: "+"Wifi正在打开...");
//                    break;
//                case WifiManager.WIFI_STATE_UNKNOWN:
//
//                    break;
//            }
        }
    }
}
